import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:openim_common/openim_common.dart';
import 'package:just_audio/just_audio.dart';

class ChatVoiceView extends StatefulWidget {
  const ChatVoiceView({
    Key? key,
    required this.message,
    required this.isISend,
  }) : super(key: key);
  
  final bool isISend;
  final Message message;

  @override
  State<ChatVoiceView> createState() => _ChatVoiceViewState();
}

class _ChatVoiceViewState extends State<ChatVoiceView>
    with TickerProviderStateMixin {
  late AudioPlayer _audioPlayer;
  bool _isPlaying = false;
  Duration _duration = Duration.zero;
  Duration _position = Duration.zero;
  late AnimationController _animationController;
  StreamSubscription? _durationSubscription;
  StreamSubscription? _positionSubscription;
  StreamSubscription? _playerCompleteSubscription;
  StreamSubscription? _playerStateSubscription;

  Message get _message => widget.message;
  SoundElem? get _soundElem => _message.soundElem;

  @override
  void initState() {
    super.initState();
    _audioPlayer = AudioPlayer();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 1000),
      vsync: this,
    );
    
    _initAudioPlayer();
  }

  void _initAudioPlayer() {
    _durationSubscription = _audioPlayer.durationStream.listen((duration) {
      if (duration != null) {
        setState(() => _duration = duration);
      }
    });

    _positionSubscription = _audioPlayer.positionStream.listen((position) {
      setState(() => _position = position);
    });

    _playerCompleteSubscription = _audioPlayer.playerStateStream.listen((state) {
      if (state.processingState == ProcessingState.completed) {
        setState(() {
          _isPlaying = false;
          _position = Duration.zero;
        });
        _animationController.stop();
        _animationController.reset();
      }
    });

    _playerStateSubscription = _audioPlayer.playingStream.listen((isPlaying) {
      setState(() {
        _isPlaying = isPlaying;
      });
    });
  }

  @override
  void dispose() {
    _durationSubscription?.cancel();
    _positionSubscription?.cancel();
    _playerCompleteSubscription?.cancel();
    _playerStateSubscription?.cancel();
    _audioPlayer.dispose();
    _animationController.dispose();
    super.dispose();
  }

  Future<void> _playPause() async {
    if (_isPlaying) {
      await _audioPlayer.pause();
      _animationController.stop();
    } else {
      String? audioPath = _soundElem?.soundPath;
      String? audioUrl = _soundElem?.sourceUrl;
      
      try {
        if (audioPath != null && File(audioPath).existsSync()) {
          await _audioPlayer.setFilePath(audioPath);
        } else if (audioUrl != null) {
          await _audioPlayer.setUrl(audioUrl);
        } else {
          // 显示错误提示
          IMViews.showToast('语音文件不存在');
          return;
        }
        await _audioPlayer.play();
        _animationController.repeat();
      } catch (e) {
        IMViews.showToast('播放失败: $e');
      }
    }
  }

  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, "0");
    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
    return "$twoDigitMinutes:$twoDigitSeconds";
  }

  Widget _buildVoiceIcon() {
    return AnimatedBuilder(
      animation: _animationController,
      builder: (context, child) {
        return Icon(
          _isPlaying ? Icons.pause : Icons.play_arrow,
          color: widget.isISend ? Colors.white : Styles.c_0C1C33,
          size: 20.w,
        );
      },
    );
  }

  Widget _buildWaveAnimation() {
    return AnimatedBuilder(
      animation: _animationController,
      builder: (context, child) {
        return Row(
          mainAxisSize: MainAxisSize.min,
          children: List.generate(3, (index) {
            return Container(
              margin: EdgeInsets.symmetric(horizontal: 1.w),
              width: 2.w,
              height: _isPlaying 
                  ? 12.h + (8.h * (0.5 + 0.5 * 
                      (1 + (index * 0.3 + _animationController.value * 2) % 1)))
                  : 8.h,
              decoration: BoxDecoration(
                color: widget.isISend ? Colors.white70 : Styles.c_8E9AB0,
                borderRadius: BorderRadius.circular(1.w),
              ),
            );
          }),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final voiceDuration = _soundElem?.duration ?? 0;
    final displayDuration = _duration.inSeconds > 0 
        ? _formatDuration(_duration) 
        : "${voiceDuration}s";

    return GestureDetector(
      onTap: _playPause,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
        constraints: BoxConstraints(
          minWidth: 80.w,
          maxWidth: 200.w,
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            _buildVoiceIcon(),
            SizedBox(width: 8.w),
            _buildWaveAnimation(),
            SizedBox(width: 8.w),
            Text(
              displayDuration,
              style: Styles.ts_0C1C33_14sp.copyWith(
                color: widget.isISend ? Colors.white : Styles.c_0C1C33,
                fontSize: 12.sp,
              ),
            ),
            if (_isPlaying && _duration.inSeconds > 0) ...[
              SizedBox(width: 4.w),
              SizedBox(
                width: 40.w,
                height: 2.h,
                child: LinearProgressIndicator(
                  value: _position.inMilliseconds / _duration.inMilliseconds,
                  backgroundColor: widget.isISend ? Colors.white30 : Styles.c_E8EAEF,
                  valueColor: AlwaysStoppedAnimation<Color>(
                    widget.isISend ? Colors.white : Styles.c_0089FF,
                  ),
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }
}